<template>
  <div
      class="diy_edit fresh_products_edits page_fresh_products"
      id="fresh_products_edit"
  >
    <el-form
        :model="form"
        ref="ruleFormRef" 
		:rules="rules"
        label-width="auto"
        class="edit_fresh_products_form"
        size="large"
    >
      <el-row class="row_e">
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="封面图" prop="cart_img">
            <el-upload class="avatar-uploader" drag accept="image/gif, image/jpeg, image/png, image/jpg"
                       action="" :http-request="upload_cart_img" :show-file-list="false">
              <img v-if="form.cart_img" :src="$fullUrl($banseUrl,form.cart_img)" class="avatar">
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="主图_1" prop="cart_img_1">
            <el-upload class="avatar-uploader" drag accept="image/gif, image/jpeg, image/png, image/jpg"
                       action="" :http-request="upload_cart_img_1" :show-file-list="false">
              <img v-if="form.cart_img_1" :src="$fullUrl($banseUrl,form.cart_img_1)" class="avatar">
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="主图_2" prop="cart_img_2">
            <el-upload class="avatar-uploader" drag accept="image/gif, image/jpeg, image/png, image/jpg"
                       action="" :http-request="upload_cart_img_2" :show-file-list="false">
              <img v-if="form.cart_img_2" :src="$fullUrl($banseUrl,form.cart_img_2)" class="avatar">
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="主图_3" prop="cart_img_3">
            <el-upload class="avatar-uploader" drag accept="image/gif, image/jpeg, image/png, image/jpg"
                       action="" :http-request="upload_cart_img_3" :show-file-list="false">
              <img v-if="form.cart_img_3" :src="$fullUrl($banseUrl,form.cart_img_3)" class="avatar">
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="主图_4" prop="cart_img_4">
            <el-upload class="avatar-uploader" drag accept="image/gif, image/jpeg, image/png, image/jpg"
                       action="" :http-request="upload_cart_img_4" :show-file-list="false">
              <img v-if="form.cart_img_4" :src="$fullUrl($banseUrl,form.cart_img_4)" class="avatar">
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="主图_5" prop="cart_img_5">
            <el-upload class="avatar-uploader" drag accept="image/gif, image/jpeg, image/png, image/jpg"
                       action="" :http-request="upload_cart_img_5" :show-file-list="false">
              <img v-if="form.cart_img_5" :src="$fullUrl($banseUrl,form.cart_img_5)" class="avatar">
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="12" class="el_form_item_warp">
          <el-form-item label="标题" prop="cart_title">
            <el-input v-model="form.cart_title" placeholder="请输入标题"></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="12" class="el_form_item_warp">
          <el-form-item label="描述" prop="cart_description">
            <el-input v-model="form.cart_description" placeholder="请输入描述"></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="原价" prop="cart_price_ago">
            <el-input-number v-model="form.cart_price_ago"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="卖价" prop="cart_price">
            <el-input-number v-model="form.cart_price"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="库存" prop="cart_inventory">
            <el-input-number v-model="form.cart_inventory" placeholder="请输入库存"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="分类" prop="cart_type">
            <el-select v-model="form.cart_type">
              <el-option v-for="(o ,i) in list_cart_goods_type" :value="o.name" :key="i"
                         :label="o.name"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
          <el-col v-if="$check_field('ger','product_code','/fresh_products/view') || $check_field('add','product_code','/fresh_products/view') || $check_field('set','product_code','/fresh_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="商品编号" prop="product_code">
                      <el-input id="product_code" v-model="form['product_code']" placeholder="请输入商品编号"
                      v-if="(form['fresh_products_id'] && $check_field('set','product_code','/fresh_products/view')) || (!form['fresh_products_id'] && $check_field('add','product_code','/fresh_products/view'))" :disabled="true"></el-input>
            <div v-else-if="$check_field('ger','product_code','/fresh_products/view')">{{form['product_code']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','order_rules','/fresh_products/view') || $check_field('add','order_rules','/fresh_products/view') || $check_field('set','order_rules','/fresh_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="下单规则" prop="order_rules">
                      <el-input id="order_rules" v-model="form['order_rules']" placeholder="请输入下单规则"
                      v-if="(form['fresh_products_id'] && $check_field('set','order_rules','/fresh_products/view')) || (!form['fresh_products_id'] && $check_field('add','order_rules','/fresh_products/view'))" :disabled="disabledObj['order_rules_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','order_rules','/fresh_products/view')">{{form['order_rules']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','seller_customers','/fresh_products/view') || $check_field('add','seller_customers','/fresh_products/view') || $check_field('set','seller_customers','/fresh_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="卖家用户" prop="seller_customers">
                              <div v-if="user_group !== '管理员'">
              {{ get_user_session_seller_customers(form['seller_customers']) }}
              <el-select v-if="(form['fresh_products_id'] && $check_field('set','seller_customers','/fresh_products/view')) || (!form['fresh_products_id'] && $check_field('add','seller_customers','/fresh_products/view'))" id="seller_customers" v-model="form['seller_customers']" :disabled="disabledObj['seller_customers_isDisabled']">
                <el-option v-for="o in list_user_seller_customers" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
                           :value="o['user_id']">
                </el-option>
              </el-select>
              <el-select v-else-if="$check_field('ger','seller_customers','/fresh_products/view')" id="seller_customers" v-model="form['seller_customers']" :disabled="true">
                <el-option v-for="o in list_user_seller_customers" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
                           :value="o['user_id']">
                </el-option>
              </el-select>
            </div>
            <el-select v-else id="seller_customers" v-model="form['seller_customers']" :disabled="disabledObj['seller_customers_isDisabled']">
              <el-option v-for="o in list_user_seller_customers" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
                         :value="o['user_id']">
              </el-option>
            </el-select>
                                  </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','store_name','/fresh_products/view') || $check_field('add','store_name','/fresh_products/view') || $check_field('set','store_name','/fresh_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="店铺名称" prop="store_name">
                      <el-input id="store_name" v-model="form['store_name']" placeholder="请输入店铺名称"
                      v-if="(form['fresh_products_id'] && $check_field('set','store_name','/fresh_products/view')) || (!form['fresh_products_id'] && $check_field('add','store_name','/fresh_products/view'))" :disabled="disabledObj['store_name_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','store_name','/fresh_products/view')">{{form['store_name']}}</div>
                    </el-form-item>
        </el-col>
          <el-col :xs="24" :sm="24" :lg="24" class="el_form_editor_warp">
          <el-form-item label="正文" prop="cart_content">
            <form_editor
                class="editor el_form_editor_warp"
                :details='form.cart_content'
                :form="form"
                @blur_comment="blur_comment"
                @update_comment="update_comment"
                :publish_flag="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="$check_action('/fresh_products/view','set') || $check_action('/fresh_products/view','add') || $check_option('/fresh_products/table','examine')" class="footer">
        <el-button type="primary" @click="onSubmit" size="large">提交</el-button>
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
      <div v-else class="footer">
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
  import {ElMessage} from "element-plus";
  import {ref, onMounted} from "vue";
  import { $post, $get } from "@/api/Api.js";
  import storageHelper from "@/libs/StorageHelper";
  import {useStore} from "vuex";
  import { useRouter, useRoute } from "vue-router";
  import {
          $check_field,
          $fullUrl,
          $banseUrl,
          $check_action,
          $getUrlParams,
          filterSensitiveWords,
          $get_stamp,
          $get_rand,
          $toTime,
          $push
  } from "@/utils/utils.js";

  let router = useRouter();
  let route = useRoute();
  let store = useStore();
  let token = storageHelper.getToken() || null;
  let UserInfo = storageHelper.getUserInfo();
  let user_id = storageHelper.getUserInfo().user_id;
  let user_group = storageHelper.getUserInfo().user_group;
  let fresh_products_id = $getUrlParams().fresh_products_id;
  let url_add = ref("/api/fresh_products/add");
  let url_set = ref("/api/fresh_products/set");
  let field = ref("fresh_products_id")
  let url_get_obj = ref("/api/fresh_products/get_obj");
  let url_upload = ref("/api/fresh_products/upload");
  let ruleFormRef = ref(null);
  
  let rules = ref({
					store_name: [
	  {
	    required: true,
	    message: "店铺名称不能为空",
	    trigger: "blur",
	  },
	],
	  });

  let disabledObj = ref({
      "product_code_isDisabled": false,
        "order_rules_isDisabled": false,
        "seller_customers_isDisabled": false,
        "store_name_isDisabled": false,
    });
  let form = ref({
    "product_code": $get_stamp(), // 商品编号
      "order_rules":  '', // 下单规则
        "seller_customers": 0, // 卖家用户
      "store_name": null, // 店铺名称
      cart_title: "",
    cart_img: "",
    cart_description: "",
    cart_price_ago: 0,
    cart_price: 0,
    cart_inventory: 0,
    cart_type: '',
    cart_content: "",
    cart_img_1: "",
    cart_img_2: "",
    cart_img_3: "",
    cart_img_4: "",
    cart_img_5: "",
    "fresh_products_id": 0, // ID
  });
  let goods_form = ref({
    goods_id: 0,
    title: "",
    img: "",
    description: "",
    price_ago: 0,
    price: 0,
    inventory: 0,
    type: '',
    content: "",
    img_1: "",
    img_2: "",
    img_3: "",
    img_4: "",
    img_5: "",
    source_table: "",
    source_field: "",
    source_id: 0,
    user_id: user_id
  })
  let list_cart_goods_type = ref([]);
  
    
    
    // 用户列表
  let list_user_seller_customers = ref([]);
        // 用户组
  let group_user_seller_customers=ref({});
          
                                                              //获取商家用户用户列表
    let get_list_user_seller_customers = async () => {
      let json = await $get("/api/user/get_list?user_group=商家用户");
      if (json.result) {
        list_user_seller_customers.value = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    }
            //获取商城卖家用户组
    let get_group_user_seller_customers = async () => {
      let json = await $get("/api/user_group/get_obj?name=商家用户");
      if (json.result) {
        group_user_seller_customers.value = json.result.obj;
      } else if (json.error) {
        console.error(json.error);
      }
    }
    //获取
    let get_user_session_seller_customers = (id) => {
      let user_id = { user_id: id };
      let source_table = group_user_seller_customers.value.source_table
      if (source_table) {
        let url = "/api/" + source_table + "/get_obj"
        $get(url, {user_id: user_id}).then((res) => {
          if (res.result && res.result.obj) {
            var arr = []
            for (let key in res.result.obj) {
              arr.push(key)
            }
            var arrForm = []
            for (let key in form.value) {
              arrForm.push(key)
            }
            form.value["seller_customers"] = id
            disabledObj.value['seller_customers' + '_isDisabled'] = true
            for (var i = 0; i < arr.length; i++) {
              if (arr[i] !== 'examine_state' && arr[i] !== 'examine_reply') {
                for (var j = 0; j < arrForm.length; j++) {
                  if (arr[i] === arrForm[j]) {
                    if (arr[i] !== "seller_customers") {
                      form.value[arrForm[j]] = res.result.obj[arr[i]]
                      disabledObj.value[arrForm[j] + '_isDisabled'] = true
                      break;
                    } else {
                      disabledObj.value[arrForm[j] + '_isDisabled'] = true
                    }
                  }
                }
              }
            }
          }
        });
      }
    }
                                        //获取商品分类
    let get_cart_goods_type = async () => {
      let json = await $get("/api/goods_type/get_list");
      if (json.result) {
        list_cart_goods_type.value = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    };
    // 富文本编辑器更新
    let update_comment = (obj) => {
        form.value.cart_content = obj;
    };
    let blur_comment = (obj) => {
        form.value.cart_content = obj;
    };
    // 封面图
    let upload_cart_img = (param) => {
        uploadFile(param.file, "cart_img");
    };
    // 上传封面图1
    let upload_cart_img_1 = (param) => {
        uploadFile(param.file, "cart_img_1");
    };
    // 上传封面图2
    let upload_cart_img_2 = (param) => {
        uploadFile(param.file, "cart_img_2");
    };
    // 上传封面图3
    let upload_cart_img_3 = (param) => {
        uploadFile(param.file, "cart_img_3");
    };
    // 上传封面图4
    let upload_cart_img_4 = (param) => {
        uploadFile(param.file, "cart_img_4");
    };
    // 上传封面图5
    let upload_cart_img_5 = (param) => {
        uploadFile(param.file, "cart_img_5");
    };
    //提交后
    let submit_after = () => {
      if (form.value[field.value]) {
        submit_goods(form.value[field.value], "set");
      } else {
        let query_form = {
          cart_title: form.value.cart_title,
          cart_description: form.value.cart_description
        }
              $get("/api/fresh_products/get_obj", query_form).then((res) => {
          console.log("商品息res", res);
          if (res.result && res.result.obj) {
            submit_goods(res.result.obj[field.value], "add");
          } else if (res.error) {
            console.error(res.error);
            ElMessage.error(res.error.message);
          }
        })
      }
    }
    let submit_goods = (source_id, add_flag) => {
      let customize_field = []
      goods_form.value = {
        goods_id: 0,
        title: form.value.cart_title,
        img: form.value.cart_img,
        description: form.value.cart_description,
        price_ago: form.value.cart_price_ago,
        price: form.value.cart_price,
        inventory: form.value.cart_inventory,
        type: form.value.cart_type,
        content: form.value.cart_content,
        img_1: form.value.cart_img_1,
        img_2: form.value.cart_img_2,
        img_3: form.value.cart_img_3,
        img_4: form.value.cart_img_4,
        img_5: form.value.cart_img_5,
        source_table: "fresh_products",
        source_field: field.value,
        source_id: source_id,
        customize_field: JSON.stringify(customize_field),
        user_id: user_id
      }
      if (add_flag === 'set') {
        delete goods_form.value.goods_id;
        delete goods_form.value.user_id;
        // 提交事件
              $post("/api/goods/set?source_table=fresh_products&source_field=" + field.value + "&source_id=" + source_id, goods_form.value).then((res) => {
          console.log("提交结果：", res)
          if (res.result) {

            ElMessage.success("修改成功");
            ruleFormRef.value.resetFields();
            router.push("./table");
          } else if (res.error) {
            console.error(res.error);
            ElMessage.error(res.error.message);
            //this.$toast(res.error.message,"error");
          }
        });
      } else {
        // 提交事件
              $post("/api/goods/add", goods_form.value).then((res) => {
          console.log("提交结果：", res)
          if (res.result) {
            ElMessage.success("添加成功");
            ruleFormRef.value.resetFields();
            router.push("./table");
          } else if (res.error) {
            console.error(res.error);
            ElMessage.error(res.error.message);
          }
        });
      }
    }
        /**
    * 上传封面图
    * @param {Object} file 文件对象
    * @param {key} 保存键名
    */
    const uploadFile = (file, key = "img") => {
        var formobj = new FormData(); // FormData 对象
        formobj.append("file", file); // 文件对象
              $upload(url_upload.value, formobj, function (json) {
          if (json.result) {
            form.value[key] = json.result.url;
          } else {
            ElMessage.error("上传失败！");
          }
        });
    };
    /**
     * 上传文件
     * @param {String} url 请求地址
     * @param {Object} body 请求参数
     * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
     * @return {Object} 返回请求结果
     */
    let $upload = async (url, body, func) => {
      url = url.replace("~/", $banseUrl);

      if (func) {
        // 如果回调函数存在, 则采用异步
              $post(url, body, {
          headers: {
            "x-auth-token": token,
            "Content-Type": "multipart/form-data",
          },
        })
            .then((res) => {
              func(res);
            })
            .catch((res) => {
              func(res);
            });
      } else {
        // 否则采用同步
        var res = await $post(url, body, {
          headers: {
            "x-auth-token": token,
            "Content-Type": "multipart/form-data",
          },
        });
        return res;
      }
    };
  //提交前验证事件
  let submit_check = () => {
                              if (!param.store_name){
      return "店铺名称不能为空";
    }
          };
  // 点击取消
  let cancel = () => {
    router.go(-1);
  };
  // 点击提交
  let onSubmit = async () => {
    let valid = await ruleFormRef.value.validate();
    if (valid) {
      // 提交表单
      if (fresh_products_id) {
        // 编辑
        delete form.value.update_time;
              $post(url_set.value + "?fresh_products_id=" + fresh_products_id, form.value).then((res) => {
          if (res.result) {
            submit_after()
          } else if (res.error) {
            ElMessage.error(res.error.message);
          }
        });

      } else {
        // 新增
              $post(url_add.value, form.value).then((res) => {
          if (res.result) {
            submit_after()
          } else if (res.error) {
            ElMessage.error(res.error.message);
          }
        });

      }
    } else {
      ElMessage.error(msg);
    }
  };
  // 查询数组对象某个是否包含某个值,返回对应对象
  let getObj = (arr, val) => {
    let obj = arr.find((item) => item.user_id == val);
    let ret = "";
    if (obj) {
      if (obj.nickname) {
        ret = obj.nickname;
      } else {
        ret = obj.username;
      }
    }
    return ret;
  };
  //获取对象之前
  let get_obj_before = (param) => {
    var formArr = "";
                                  if(form.value && formArr){
      Object.keys(form.value).forEach(key => {
        Object.keys(formArr).forEach(dbKey => {
          if(key === dbKey){
            disabledObj.value[key+'_isDisabled'] = true;
          }
        })
      })
    }
                    localStorage.removeItem('form')
    return param;
  }
  // js判断字段是否是时间戳格式
  let isTimestamp = (value) => {
    return /^\d{10}$/.test(value) || /^\d{13}$/.test(value);
  }
  //获取对象之后
  let get_obj_after = (json, func) => {
                                                                                                                          }
  let is_view = () => {
    var bl = user_group == "管理员";
    if (!bl) {
      bl = $check_action('/fresh_products/table', 'add');
      console.log(bl ? "你有表格添加权限视作有添加权限" : "你没有表格添加权限");
    }
    if (!bl) {
      bl = $check_action('/fresh_products/table', 'set');
      console.log(bl ? "你有表格添加权限视作有修改权限" : "你没有表格修改权限");
    }
    if (!bl) {
      bl = $check_action('/fresh_products/view', 'add');
      console.log(bl ? "你有视图添加权限视作有添加权限" : "你没有视图添加权限");
    }
    if (!bl) {
      bl = $check_action('/fresh_products/view', 'set');
      console.log(bl ? "你有视图修改权限视作有修改权限" : "你没有视图修改权限");
    }
    if (!bl) {
      bl = $check_action('/fresh_products/view', 'get');
      console.log(bl ? "你有视图查询权限视作有查询权限" : "你没有视图查询权限");
    }
    console.log(bl ? "具有当前页面的查看权，请注意这不代表你有字段的查看权" : "无权查看当前页，请注意即便有字段查询权限没有页面查询权限也不行");
    return bl;
  }
  // 获取详情
  let get_fresh_products_obj = async () => {
    let list = await $get("/api/fresh_products/get_obj?fresh_products_id=" + fresh_products_id);
    form.value = list.result.obj;
    get_obj_after();
  };
  onMounted(() => {
                get_list_user_seller_customers();
          get_group_user_seller_customers();
                get_cart_goods_type();
    if (fresh_products_id) {
      get_fresh_products_obj();
    }else {
      get_obj_before();
      get_obj_after();
    }

  });
</script>

<style scoped lang="less">
  .diy_edit {
    width: 100%;

    .edit_fresh_products_form {
      max-width: 80%;
      margin: 90px auto;

      .fn {
        width: 100%;
      }
    }

    img {
      width: 100px;
      height: 100px;
    }

    .edit_list_fresh_products_sell {
      width: 80%;
      margin: 90px auto;
    }

    .footer {
      text-align: center;
    }
  }
</style>
  